package com.ledong;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

/**
 * JDBC工具类
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-4-8
 */
public class JdbcUtil {

    // 静态块，在类加载的时候就加载数据库连接驱动
    static {
        String driverName = "oracle.jdbc.driver.OracleDriver";
        try {
            Class.forName(driverName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到connection连接
     * 
     * @return
     */
    public static Connection getConn() {
        String url_oracle = "jdbc:oracle:thin:@172.17.1.6:1521:tarena";// Oracle数据库连接地址
        String userName = "hfsd0909"; // 用户名
        String pwd = "tarena"; // 登陆密码
        Connection con = null; // 接口不能被new，设置为null
        try {
            con = DriverManager.getConnection(url_oracle, userName, pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return con;
    }

    /**
     * 关闭数据库连接
     * 
     * @param rs
     * @param stmt
     * @param con
     */
    public static void close(ResultSet rs, Statement stmt, Connection con) {
        try {
            if (rs != null)
                rs.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        try {
            if (con != null)
                con.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 转换
     * 
     * @param num
     * @return
     */
    public static Integer toInt(String num) {
        Integer i = null;
        try {
            i = Integer.parseInt(num);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 打印结果集
     * 
     * @param rs
     */
    public static void printRs(ResultSet rs) {
        try {
            ResultSetMetaData meta = rs.getMetaData();
            int cols = meta.getColumnCount();
            StringBuffer sb = new StringBuffer();
            while (rs.next()) {
                for (int i = 1; i <= cols; i++) {
                    sb.append(meta.getColumnName(i) + "=");
                    sb.append(rs.getString(i) + "  ");
                }
                sb.append("\n");
            }
            System.out.print(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
